const path = require('path');

const mongoose = koahub.mongoose;
const Schema = koahub.Schema;
const ObjectId = Schema.Types.ObjectId;

// 定义表结构
let schema = new Schema({
    name: { //文件原始名称
        type: String,
        required: true
    },
    ext: { //文件扩展名
        type: String,
        required: true
    },
    storage: { //存储引擎
        type: String,
        required: true,
        default: 'local'
    },
    saveName: { //保存的文件名
        type: String,
        // required: true
    },
    savePath: { //存放的路径
        type: String,
        // required: true
    },
    fileType: { //image/jpeg
        type: String,
        required: true,
        default: 'image/jpeg'
    },
    fileSize: Number,
    md5: String, //校验码，避免重复存储
    sha1: String //校验码，避免重复存储
}, {timestamps: {}, collection: 'Picture'});


schema.virtual('url').get(function () {
    if (this.storage === 'local') {
        return `/public/uploads/${this.savePath}${this.saveName}`;
    }
    return `${this.savePath}${this.saveName}`;
});

schema.statics.uploadImage = async function (file) {

    const moment = require('moment');
    const uuid = require('node-uuid');
    const fs = require('fs-promise');
    const md5 = require('md5');

    let ext = '';  //后缀名
    switch (file.type) {
        case 'image/pjpeg':
            ext = 'jpg';
            break;
        case 'image/jpeg':
            ext = 'jpg';
            break;
        case 'image/png':
            ext = 'png';
            break;
        case 'image/x-png':
            ext = 'png';
            break;
    }
    const savepath = moment().format('YYYY-MM-DD') + '/';
    const savename = uuid.v1() + '.' + ext;

    //计算md5校验值，如果相同则不保存新的
    let buf = await fs.readFile(file.path);
    let checksum_md5 = md5(buf);

    const oldfile = await this.findOne({md5: checksum_md5});
    if (oldfile) {
        //existed the same file
        await fs.unlink(file.path);
        return oldfile;
    } else {

        const err = await fs.move(file.path, path.resolve('www/public/uploads/', savepath, savename));

        // const err = await fs.move(file.path, 'www/public/uploads/' + savepath + savename);
        if (!err) {
            const data = {
                name: file.name,
                ext: ext,
                fileType: file.type,
                saveName: savename,
                savePath: savepath,
                storage: 'local',
                md5: checksum_md5
            };

            return await this.saveOrUpdate(data);
        } else {
            return false;
        }
    }
};


// 数据库中的集合名称, 不存在会创建.
let Picture = mongoose.model('Picture', schema);

//插入测试数据
Picture.findOne(function (err, data) {
    if (!data) {
        //插入测试数据
        // for (let i = 0; i <= 100; i = i + 1) {
        //     let ext = 'jpg';
        //     const savepath = moment().format('YYYY-MM-DD') + '/';
        //     const savename = uuid.v1() + '.' + ext;
        //
        //     let picture = new Picture({
        //         name: `filename-${i}`,
        //         ext: ext,
        //         saveName: savename,
        //         savePath: savepath,
        //         fileType: 'image/jpeg'
        //     });
        //     picture.save();
        // }
        //
        // for (let i = 0; i <= 100; i = i + 1) {
        //     let ext = 'jpg';
        //     const savepath = moment().format('YYYY-MM-DD') + '/';
        //     const savename = uuid.v1() + '.' + ext;
        //
        //     let picture = new Picture({
        //         name: `filename-${i}`,
        //         ext: ext,
        //         saveName: savename,
        //         savePath: savepath,
        //         fileType: 'image/jpeg',
        //         storage: 'qiniu'
        //     });
        //     picture.save();
        // }
    }
});

module.exports = Picture;